package controllers

import (
	"Blog/models"
	"errors"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"strings"
)

type UserController struct{
	BaseController
}
func (c *UserController) Login(){
	if c.Ctx.Input.IsGet(){
		c.TplName="login.html"
	}
	if c.Ctx.Input.IsPost(){
        username:=c.JugeNull("username","用户名不能为空")
		password:=c.JugeNull("password","密码不能为空")
		num,err,user:=models.QueryUser(username,password)
		if num==0||err!=nil{
               c.Abort500(errors.New("账号或者密码错误"))
		}
		c.SetSession(SESSION_USER_KEY,user)   //将user保存到session中
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"action":"/Auth/Index"  ,   //返回自定义错误
		}
		_ = c.ServeJSON()
	}
}
func (c *UserController) LoginOut(){
	_ = c.DelSession(SESSION_USER_KEY) //删除session
	c.Redirect(beego.URLFor("UserController.Login"),302)
}
func (c *UserController) Reg(){
	if c.Ctx.Input.IsGet(){
		c.TplName="reg.html"
	}
	if c.Ctx.Input.IsPost(){
		username:=c.JugeNull("username","用户名不能为空")
		password:=c.JugeNull("password","密码不能为空")
		email:=c.JugeNull("email","邮箱不能为空")
		rpassword:=c.JugeNull("rpassword","确认密码不能为空")
		if strings.Compare(password,rpassword)!=0{
			c.Abort500(errors.New("两次输入的密码不相同"))
		}
        if num,err:=models.QueryUserByName(username);err==nil||num!=0{
        	fmt.Println(err)
        	fmt.Println(num)
        	c.Abort500(errors.New("用户名已经被人注册"))
		}
		val:=models.User{
			Name:username,
			Pwd:password,
			Email: email,
			Head: "/static/images/item.png",
		}
		if err:=models.Register(val);err!=nil{
			c.Abort500(err)
		}
		c.Data["json"]=map[string]interface{}{
			"code":0,
			"action":"/user/login",
		}
		_ = c.ServeJSON()
		return
	}
}
